package com.applink.sell_proof.fragment;

import java.util.List;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.applink.sell_proof.BaseClaim;
import com.applink.sell_proof.R;
import com.applink.sell_proof.builder.ProofBuilder;
import com.applink.sell_proof.model.Product;

public class InvoiceDetail extends SherlockFragment {

	public static final String TAG = "InvoiceDetail";

	protected ProofBuilder productBuilder;

	protected ListView mListView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View layout = inflater.inflate(R.layout.invoice_detail, null);

		int height = (int) (getResources().getDisplayMetrics().heightPixels);

		mListView = (ListView) layout.findViewById(android.R.id.list);
		mListView.getLayoutParams().height = height / 2;

		initProductBuilder(mListView);

		InvoiceBrieftFragment invoiceBrieft = (InvoiceBrieftFragment) getActivity()
				.getSupportFragmentManager().findFragmentByTag(
						"InvoiceBrieftFragment");

		if (invoiceBrieft != null) {
			((TextView) layout.findViewById(R.id.invoice_no))
					.setText(invoiceBrieft.getInvoiceNo());
			((TextView) layout.findViewById(R.id.invoice_customer_name))
					.setText(invoiceBrieft.getCustomerName());
		}

		setHasOptionsMenu(true);
		return layout;
	}

	protected void initProductBuilder(ListView l) {

		productBuilder = new ProofBuilder(getActivity(), l);

		List<Product> products = ((BaseClaim) getActivity()).getProducts();

		if (products.size() == 0)
			products.add(new Product());

		productBuilder.setData(products);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.claim_detail_menu, menu);
	}

	@Override
	public void onPrepareOptionsMenu(Menu menu) {
		if (menu != null)
			menu.removeItem(R.id.claim_detail);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_add_product:
			productBuilder.addProduct();
			break;
		case R.id.menu_header:
			((BaseClaim) getActivity())
					.setListProducts((List<Product>) getProducts());

			FragmentTransaction transaction = getActivity()
					.getSupportFragmentManager().beginTransaction();

			transaction.remove(this);
			transaction.commit();
			break;
		default:
			break;
		}
		return false;
	}

	public void setProductModel(Product productModel) {
		productBuilder.setProductModel(productModel);
	}

	@SuppressWarnings("unchecked")
	public List<Product> getProducts() {
		return (List<Product>) productBuilder.getData();
	}
}
